package com.java.a02UDPDemo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class ReceiveMessageDemo {
    public static void main(String[] args) throws IOException {
         //1.创建接收端的socket对象
        //细节：在接收的时候一定要绑定端口，而且绑定的端口必须与发送端绑定的端口保持一致
        DatagramSocket ds = new DatagramSocket(10086);

        //2.接收数据包
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
        ds.receive(dp);

        //3.解析数据包
        byte[] data = dp.getData();
        int length = dp.getLength();
        InetAddress address = dp.getAddress();
        int port = dp.getPort();
        System.out.println("接收到数据:" + new String(data, 0, length));
        System.out.println("该数据来自于IP地址" + address + "的电脑" + port + "这个端口发出的");

        //4.释放资源
        ds.close();
    }
}
